package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
)

var todoFile = filepath.Join(os.Getenv("HOME"), ".todo")

var remove = flag.Int("rm", -1, "index of item to remove")

func main() {
	flag.Parse()

	if p := os.Getenv("TODOFILE"); p != "" {
		todoFile = p
	}

	// Read the JSON-encoded todo list into items.
	var items []string
	f, err := os.Open(todoFile)
	if err != nil && !os.IsNotExist(err) {
		log.Fatal(err)
	} else if err == nil {
		json.NewDecoder(f).Decode(&items)
		f.Close()
	}

	doWrite := true
	a := flag.Args()
	switch {
	case len(a) > 0:
		// Join command-line arguments together and add to items.
		s := strings.Join(a, " ")
		items = append(items, s)
	case *remove >= 0:
		// Create a newItems slice without the specified element.
		var newItems []string
		for i, s := range items {
			if i != *remove {
				newItems = append(newItems, s)
			}
		}
		// Replace items with newItems.
		items = newItems
	default:
		doWrite = false
	}

	if doWrite {
		// Write the JSON-encoded todo list to disk.
		f, err := os.OpenFile(todoFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
		if err != nil {
			log.Fatal(err)
		}
		err = json.NewEncoder(f).Encode(items)
		if err != nil {
			log.Fatal(err)
		}
		f.Close()
	}

	// List the items.
	for i, s := range items {
		fmt.Printf("%d %s\n", i, s)
	}
}
